const UserApi = require('../../../api/user.js');
const CommonApi = require('../../../api/common.js');
const regExpUtil = require('../../utils/regExp.js');
const commonUtil = require('../../../utils/common.js');

Page({
  data: {
    loginType: 'psw',
    tickTip: '获取验证码',
    formModel: {
      username: null,
      password: null,
      loginFrom: 'xcx'
    },
    phoneModel: {
      phoneNumber: null,
      captcha: null,
      code: null,
      loginFrom: 'xcx'
    },
    isPswAgree: false,
    isAgree: false,
    timers: 60,
    countDown: null,
    phoneNumber: null,
    redirect_uri: '/pages/index/index',
    redirect_uri_type: 'tab',
  },

  onLoad(options) {
    if (options.redirect_uri) {
      this.setData({redirect_uri: options.redirect_uri})
    }
    if (options.redirect_uri_type) {
      this.setData({redirect_uri_type: options.redirect_uri_type})
    }
  },

  onReady() {},

  onShow() {
    wx.removeStorageSync('token')
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('userService')
  },

  onHide() {},
  toggleType(e){
    var type = e.currentTarget.dataset.type;
    this.setData({loginType: type})
  },
  toRegister(){
    wx.redirectTo({
      url: '/packageA/pages/register/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
    })
  },
  forgetPsw(){
    wx.redirectTo({
      url: '/packageA/pages/forgetPsw/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
    })
  },
  startInterval(){
    let that = this;
    let countDownNum = that.data.timers;

    that.data.countDown = setInterval(()=>{
      if (countDownNum < 1) {
        that.setData({tickTip: '获取验证码', timers: 60});
        clearInterval(that.data.countDown);
      } else {
        countDownNum--;
        that.setData({
          timers: countDownNum,
          tickTip: countDownNum+'s后重发'
        })
      }
    }, 1000)
  },
  // 获取验证码
  getVerifyCode(){
    if (this.data.tickTip != '获取验证码') return;
    if (!this.data.phoneModel.phoneNumber) {
      wx.showToast({icon: 'none', title: '请输入手机号码'})
    } else if (this.data.phoneModel.phoneNumber && !regExpUtil.isPhoneNumber(this.data.phoneModel.phoneNumber)) {
      wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
    } else {
      this.setData({dialogVisible: true});
    }
  },
  // 获取图形验证码弹窗传递来的数据
  getCaptchaData(e){
    console.log(e);
    this.setData({
      dialogVisible: false, 
      ['phoneModel.captcha']: e.detail.captcha,
      ['phoneModel.captchaId']: e.detail.captchaId
    })
    this.getPhoneNumberRegistered()
  },
  // 判断手机号是否注册，已注册才发送短信验证码
  getPhoneNumberRegistered(){
    UserApi.getPhoneNumberRegistered({phoneNumber: this.data.phoneModel.phoneNumber}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        if (res.data) {
            this.sendGzhSms();
        } else {
            ElMessage.info("手机号码未注册");
            return false;
        }
      }
    })
  },
  // 公众号发送短信验证码
  sendGzhSms(){
    CommonApi.sendGzhSms({phoneNumber: this.data.phoneModel.phoneNumber}).then(res=>{
      if (res.retCode == "000000" && res.errCode == "000000") {
        wx.showToast({icon: 'success', title: '短信验证码发送成功'});
        this.startInterval()
      }
    })
  },
  handleInput(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'username') {
      this.setData({['formModel.username']: value})
    } else if (target == 'password') {
      this.setData({['formModel.password']: value})
    } else if (target == 'phoneNumber') {
      this.setData({['phoneModel.phoneNumber']: value})
    } else if (target == 'code') {
      this.setData({['phoneModel.code']: value})
    }
  },
  checkboxChange(e){
    let target = e.currentTarget.dataset.item;
    let value = e.detail.value;
    if (target == 'isPswAgree') {
      this.setData({isPswAgree: value.length > 0})
    } else if (target == 'isAgree') {
      this.setData({isAgree: value.length > 0})
    }
  },
  formSubmit(e){
    const that = this;
    if (this.data.loginType == 'psw') {
      if (!this.data.formModel.username) {
        wx.showToast({icon: 'none', title: '请输入手机号/用户名'});
      } else if (!this.data.formModel.password) {
        wx.showToast({icon: 'none', title: '请输入登录密码'});
      } else {
        if (!this.data.isPswAgree) {
          wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'});
          return;
        }
        CommonApi.passwordLogin({...this.data.formModel, loginFrom: 'xcx'}).then(loginRes=>{
          if (loginRes.retCode == "000000" && loginRes.errCode == "000000") {
            wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.formModel.username});
            wx.setStorageSync('token', loginRes.data.accessToken);
            setTimeout(()=>{
              that.getLoginUser()
            }, 200)
          } else {
            wx.showToast({icon: 'error', title: loginRes.errMsg})
          }
        })
      }
    } else {
      if (!this.data.phoneModel.phoneNumber) {
        wx.showToast({icon: 'none', title: '请输入手机号码'})
      } else if (!regExpUtil.isPhoneNumber(this.data.phoneModel.phoneNumber)) {
        wx.showToast({icon: 'none', title: '请输入正确的手机号码'})
      } else if (!this.data.phoneModel.code) {
        wx.showToast({icon: 'none', title: '请输入验证码'})
      } else {
        if (!this.data.isAgree) {
          wx.showToast({icon: 'none', title: '请勾选阅读并接受用户协议'});
          return;
        }
        CommonApi.phoneLogin({...this.data.phoneModel, loginFrom: 'xcx'}).then(loginRes=>{
          if (loginRes.retCode == "000000" && loginRes.errCode == "000000") {
            this.setData({phoneNumber: this.data.phoneModel.phoneNumber})
            wx.setStorageSync('lastLoginInfo', {phoneNumber: this.data.phoneModel.phoneNumber});
            wx.setStorageSync('token', loginRes.data.accessToken);
            setTimeout(()=>{
              that.getLoginUser()
            }, 200)
          } else {
            wx.showToast({icon: 'error', title: loginRes.errMsg})
          }
        })
      }
    }
  },
  // 查询登录用户详情
  getLoginUser(){
    UserApi.getLoginUser().then(userRes=>{
      if (userRes.retCode == "000000" && userRes.errCode == "000000") {
        this.setData({phoneNumber: userRes.data.phoneNumber});
        wx.setStorageSync('userInfo', userRes.data)
        wx.removeStorageSync('loginInfo')
        commonUtil.getUserServiceState();

        if (this.data.loginType == 'psw') {
          if (!userRes.data.setPassword || !userRes.data.activated) {
            wx.setStorageSync('resetInfo', {'action': 'set', phoneNumber: userRes.data.phoneNumber})
            wx.redirectTo({
              url: '/packageA/pages/forgetPsw/index?redirect_uri='+this.data.redirect_uri+'&redirect_uri_type='+this.data.redirect_uri_type,
            })
          } else {
            if (this.data.redirect_uri_type == 'tab') {
              wx.switchTab({url: this.data.redirect_uri})
            } else if (this.data.redirect_uri_type == 'link') {
              wx.redirectTo({url: this.data.redirect_uri})
            }
          }
        } else {
          if (this.data.redirect_uri_type == 'tab') {
            wx.switchTab({url: this.data.redirect_uri})
          } else if (this.data.redirect_uri_type == 'link') {
            wx.redirectTo({url: this.data.redirect_uri})
          }
        }
        wx.showToast({icon: 'success', title: '登录成功'})
      }
    })
  },
  checkProtocol() {
    wx.navigateTo({
      url: '/packageA/pages/protocol/index',
    })
  },
  onUnload() {

  },
})